package com.yanjr.modules.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yanjr.common.utils.Global;
import com.yanjr.common.utils.StringUtils;
import com.yanjr.common.web.BaseController;
import com.yanjr.modules.sys.entity.Area;
import com.yanjr.modules.sys.entity.Office;
import com.yanjr.modules.sys.service.AreaService;
import com.yanjr.modules.sys.service.OfficeService;
import com.yanjr.modules.sys.utils.UserUtils;

/**
 * 机构Controller
 * 
 * @ClassName: OfficeController 
 * @author yanjr big123@126.com 
 * @date 2016年4月5日 下午3:17:17
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;
	@Autowired
	private AreaService areaService;
	
	@ModelAttribute("office")
	public Office get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return officeService.get(id);
		}else{
			return new Office();
		}
	}

	@RequestMapping({"list", ""})
	public String list(Office office, Model model) {
		office.setId("1");
		
		model.addAttribute("office", office);
		List<Office> list = new ArrayList<>();
		List<Office> sourcelist = officeService.findAll();
		UserUtils.sortOfficeList(list, sourcelist, office.getId());
        model.addAttribute("list", list);
		return "modules/sys/officeList";
	}
	
	@RequestMapping("form")
	public String form(Office office, Model model) {
//		User user = UserUtils.getUser();
		
		if(StringUtils.isEmpty(office.getParentId())) {
			office.setParentId("1");
		}
		Office parent = officeService.get(office.getParentId());
		Area area = new Area();
		if(StringUtils.isNotEmpty(office.getAreaId())) {
			area = areaService.get(office.getAreaId());
		} else if(parent != null && StringUtils.isNotEmpty(parent.getAreaId())) {
			area = areaService.get(parent.getAreaId());
		}
		model.addAttribute("area", area);
		model.addAttribute("parent", parent);
		model.addAttribute("office", office);
		return "modules/sys/officeForm";
	}
	
	@RequestMapping("save")
	public String save(Office office, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, office)) {
			return form(office, model);
		}
		officeService.save(office);
		addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");
		return "redirect:" + Global.getAdminPath() + "/sys/office/";
	}
	
	@RequestMapping("delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		if (UserUtils.isOfficeRoot(id)) {
			addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
		} else {
			officeService.delete(id);
			addMessage(redirectAttributes, "删除机构成功");
		}
		return "redirect:" + Global.getAdminPath() + "/sys/office/";
	}

	/**
	 * 获取机构JSON数据。
	 * @param extId 排除的ID
	 * @param type	类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade 显示级别
	 * @param response
	 * @return
	 */
	@RequiresUser
	@ResponseBody
	@RequestMapping("treeData")
	public List<Map<String, Object>> treeData(HttpServletResponse response,
			@RequestParam(required = false) String extId,
			@RequestParam(required = false) Long type,
			@RequestParam(required = false) Long grade) {
		
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = new ArrayList<>();
		
//		User user = UserUtils.getUser();
		List<Office> list = officeService.findAll();
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			
			if ((extId == null || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && Integer.parseInt(e.getType()) <= type.intValue()))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))){
				
				Map<String, Object> map = new HashMap<>();
				map.put("id", e.getId());
//				map.put("pId", !user.isAdmin() && e.getId().equals(user.getOffice().getId())?0:e.getParent()!=null?e.getParent().getId():0);
				map.put("pId", e.getParentId() != null ? e.getParentId() : 0);
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
}
